<!--
  Copyright [2025] [OBARA (Nanjing) Electromechanical Co., Ltd]

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->


{% extends 'base.html' %}

{% block title %}搜索结果 - 小原焊枪选型数据库{% endblock %}

{% block extra_css %}
<style>
    /* 1. 搜索结果宽度不够需要多行显示时增加行高让看起来美观一点，注意文字外部的高亮不要重叠 */
    .table-responsive table.table td {
        padding-top: 0.75rem; /* 增加顶部内边距 */
        padding-bottom: 0.75rem; /* 增加底部内边距 */
        vertical-align: middle; /* 垂直居中 */
        line-height: 1.5; /* 增加行高，让多行文本更易读 */
    }

    /* 确保高亮文本在多行时不会显得拥挤，且高亮区域美观 */
    .table-responsive table.table td .highlight-field {
        /* 如果高亮是背景色，增加行高和内边距有助于视觉分离 */
        padding: 0.1rem 0.2rem; /* 稍微增加高亮区域的内边距 */
        border-radius: 0.25rem; /* 轻微圆角 */
        display: inline; /* 确保是行内元素，以便文本换行 */
        /* box-decoration-break 属性用于控制元素在行内断开时的背景、边框、阴影等表现 */
        box-decoration-break: clone; /* 尝试此属性，可能改善多行高亮外观 */
        -webkit-box-decoration-break: clone; /* Webkit前缀 */
    }

    /* 2. <option value="pdf">仅PDF</option>、<option value="step">仅STEP</option>和<option value="both">PDF和STEP</option>三个选项按钮美观一点，不要下拉，要有边框，不要和原背景冲突 */
    .file-type-buttons .btn {
        border-radius: 0.25rem; /* 保持按钮圆角 */
        margin-right: 0.5rem; /* 按钮之间间隔 */
        min-width: 80px; /* 确保按钮宽度一致 */
    }
    .file-type-buttons .btn:last-child {
        margin-right: 0; /* 最后一个按钮不需要右边距 */
    }
    /* 激活状态的按钮样式 */
    .file-type-buttons .btn.active {
        background-color: var(--bs-primary); /* 使用主题主色作为背景 */
        border-color: var(--bs-primary); /* 边框颜色与背景一致 */
        color: white; /* 文字颜色为白色 */
    }

    /* 图片预览样式 */
    .image-preview {
        transition: transform 0.2s ease;
        border: 1px solid #dee2e6;
    }
    
    .image-preview:hover {
        transform: scale(1.05);
        border-color: #007bff;
        box-shadow: 0 2px 8px rgba(0,123,255,0.25);
    }

    /* 图片预览模态框样式 */
    .modal-lg {
        max-width: 90vw;
    }
    
    #previewImage {
        max-width: 100%;
        max-height: 80vh;
        object-fit: contain;
        border-radius: 0.375rem;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }
</style>
{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <!-- 搜索结果头部 -->
        <div class="results-header fade-in-up">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h2 class="mb-1">
                        <i class="bi bi-search me-2"></i>
                        搜索结果
                    </h2>
                    <p class="mb-0">共找到 {{ total_results }} 个匹配的产品</p>
                </div>
                <div>
                    <a href="{% url 'clamps:search' %}" class="btn btn-light">
                        <i class="bi bi-arrow-left me-2"></i>
                        返回搜索
                    </a>
                </div>
            </div>
        </div>
        
        {% if page_obj %}
            <!-- 搜索结果表格 -->
            <div class="card fade-in-up">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">搜索结果列表</h5>
                    <div>
                        <div class="input-group">
                            <!-- 替换下拉框为按钮组 -->
                            <div class="btn-group file-type-buttons" role="group" aria-label="文件类型选择">
                                <button type="button" class="btn btn-outline-primary btn-sm" data-file-type="pdf">仅PDF</button>
                                <button type="button" class="btn btn-outline-primary btn-sm active" data-file-type="step">仅STEP</button>
                                <button type="button" class="btn btn-outline-primary btn-sm" data-file-type="both">PDF和STEP</button>
                            </div>
                            <button id="batchDownloadBtn" class="btn btn-primary btn-sm" disabled>
                                <i class="bi bi-download me-2"></i>批量下载选中项
                            </button>
                        </div>
                    </div>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead>
                                <tr>
                                    <th width="5%"><input type="checkbox" id="selectAll"></th>
                                    <th width="5%">序号</th>
									<!--
                                    <th width="20%" class="highlight-field">描述</th>
									-->
                                    <th width="15%" class="highlight-field">图号1(o)</th>
                                    <th width="15%" class="highlight-field">喉深</th>
                                    <th width="15%" class="highlight-field">喉宽</th>
                                    <th width="18%" class="highlight-field">变压器</th>
                                    <th width="15%">预览图</th>
                                    <th width="12%">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for product in page_obj %}
                                    <tr class="product-row" data-product-id="{{ product.id }}">
                                        <td><input type="checkbox" class="product-checkbox" value="{{ product.id }}"></td>
                                        <td>{{ forloop.counter0|add:page_obj.start_index }}</td>
										<!--
                                        <td>
                                            <span class="highlight-field" onclick="viewDetail({{ product.id }})">
                                                {{ product.description|default:"--" }}
                                            </span>
                                        </td>
										-->
                                        <td>
                                            <span class="highlight-field" onclick="viewDetail({{ product.id }})">
                                                {{ product.drawing_no_1|default:"--" }}
                                            </span>
                                        </td>
                                        <td>
                                            <span class="highlight-field" onclick="viewDetail({{ product.id }})">
                                                {% if product.throat_depth %}
                                                    {{ product.throat_depth }}
                                                {% else %}
                                                    --
                                                {% endif %}
                                            </span>
                                        </td>
                                        <td>
                                            <span class="highlight-field" onclick="viewDetail({{ product.id }})">
                                                {% if product.throat_width %}
                                                    {{ product.throat_width }}
                                                {% else %}
                                                    --
                                                {% endif %}
                                            </span>
                                        </td>
                                        <td>
                                            <span class="highlight-field" onclick="viewDetail({{ product.id }})">
                                                {{ product.transformer|default:"--" }}
                                            </span>
                                        </td>
                                        <td>
                                            {% if product.bmp_file_path %}
                                             <img src="{% url 'clamps:protected_media' path=product.bmp_file_path %}" 
                                                     class="image-preview" 
                                                onclick="previewImage('{% url 'clamps:protected_media' path=product.bmp_file_path %}', '{{ product.drawing_no_1|default:"未知产品" }}')"                                      alt="产品预览图"
                                                     style="width: 60px; height: 60px; object-fit: cover; cursor: pointer; border-radius: 4px;"
                                                     onerror="this.style.display='none'; this.nextElementSibling.style.display='block';"
                                                     title="点击图片放大查看">
                                                <span class="text-muted" style="display: none;">无图片</span>
                                            {% else %}
                                                <span class="text-muted">无图片</span>
                                            {% endif %}
                                        </td>
                                        <td>
                                            <div class="btn-group-vertical btn-group-sm">
                                                <a href="{% url 'clamps:product_detail' product.id %}" 
                                                   class="btn btn-outline-primary btn-sm">
                                                    <i class="bi bi-eye me-1"></i>详情
                                                </a>
                                                {% if product.pdf_file_path %}
                                                    <a href="{% url 'clamps:download_file' product.id 'pdf' %}" 
                                                       class="btn btn-outline-success btn-sm delayed-download"
                                                       data-product-id="{{ product.id }}" 
                                                       data-file-type="pdf">
                                                        <i class="bi bi-download me-1"></i>PDF
                                                    </a>
                                                {% endif %}

                                                {% if product.step_file_path %}
                                                    <a href="{% url 'clamps:download_file' product.id 'step' %}" 
                                                       class="btn btn-outline-info btn-sm delayed-download"
                                                       data-product-id="{{ product.id }}" 
                                                       data-file-type="step">
                                                        <i class="bi bi-download me-1"></i>STEP
                                                    </a>
                                                {% endif %}
                                            </div>
                                        </td>
                                    </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- 分页导航 -->
            {% if page_obj.has_other_pages %}
                <nav aria-label="搜索结果分页" class="mt-4">
                    <ul class="pagination justify-content-center">
                        {% if page_obj.has_previous %}
                            <li class="page-item">
                                <a class="page-link" href="?{% for key, value in query_params.items %}{{ key }}={{ value }}&{% endfor %}page=1">
                                    <i class="bi bi-chevron-double-left"></i>
                                </a>
                            </li>
                            <li class="page-item">
                                <a class="page-link" href="?{% for key, value in query_params.items %}{{ key }}={{ value }}&{% endfor %}page={{ page_obj.previous_page_number }}">
                                    <i class="bi bi-chevron-left"></i>
                                </a>
                            </li>
                        {% endif %}
                        
                        {% for num in page_obj.paginator.page_range %}
                            {% if page_obj.number == num %}
                                <li class="page-item active">
                                    <span class="page-link">{{ num }}</span>
                                </li>
                            {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                                <li class="page-item">
                                    <a class="page-link" href="?{% for key, value in query_params.items %}{{ key }}={{ value }}&{% endfor %}page={{ num }}">{{ num }}</a>
                                </li>
                            {% endif %}
                        {% endfor %}
                        
                        {% if page_obj.has_next %}
                            <li class="page-item">
                                <a class="page-link" href="?{% for key, value in query_params.items %}{{ key }}={{ value }}&{% endfor %}page={{ page_obj.next_page_number }}">
                                    <i class="bi bi-chevron-right"></i>
                                </a>
                            </li>
                            <li class="page-item">
                                <a class="page-link" href="?{% for key, value in query_params.items %}{{ key }}={{ value }}&{% endfor %}page={{ page_obj.paginator.num_pages }}">
                                    <i class="bi bi-chevron-double-right"></i>
                                </a>
                            </li>
                        {% endif %}
                    </ul>
                </nav>
                
                <div class="text-center text-muted">
                    第 {{ page_obj.number }} 页，共 {{ page_obj.paginator.num_pages }} 页
                    (显示第 {{ page_obj.start_index }} - {{ page_obj.end_index }} 条记录，共 {{ total_results }} 条)
                </div>
            {% endif %}
            
        {% else %}
            <!-- 无搜索结果 -->
            <div class="text-center py-5 fade-in-up">
                <div class="card">
                    <div class="card-body py-5">
                        <i class="bi bi-search text-muted" style="font-size: 4rem;"></i>
                        <h3 class="mt-3 text-muted">未找到匹配的产品</h3>
                        <p class="text-muted">请尝试调整搜索条件或使用不同的关键词</p>
                        <a href="{% url 'clamps:search' %}" class="btn btn-primary">
                            <i class="bi bi-arrow-left me-2"></i>
                            重新搜索
                        </a>
                    </div>
                </div>
            </div>
        {% endif %}
        
        <!-- 搜索条件摘要 -->
        {% if query_params %}
            <div class="card mt-4 fade-in-up">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="bi bi-funnel me-2"></i>
                        当前搜索条件
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        {% for key, value in query_params.items %}
                            {% if value %}
                                <div class="col-md-3 mb-2">
                                    <span class="badge bg-primary">
                                        {{ key }}: {{ value }}
                                    </span>
                                </div>
                            {% endif %}
                        {% endfor %}
                    </div>
                </div>
            </div>
        {% endif %}
    </div>
</div>

<!-- 图片预览模态框 -->
<div class="modal fade" id="imagePreviewModal" tabindex="-1" aria-labelledby="imagePreviewModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" style="max-width: 800px;">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="imagePreviewModalLabel">
                    <i class="bi bi-image me-2"></i>
                    产品预览图
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body text-center p-4">
                <img id="previewImage" src="" alt="产品预览图" class="img-fluid" >
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    function viewDetail(productId) {
        window.location.href = `/product/${productId}/`;
    }
    
    // 图片预览功能 - 增强版，与product_detail.html保持一致
    function previewImage(imageSrc, productName) {
        const modal = new bootstrap.Modal(document.getElementById('imagePreviewModal'));
        const previewImg = document.getElementById('previewImage');
        const modalTitle = document.getElementById('imagePreviewModalLabel');
        
        // 设置图片源和标题
        previewImg.src = imageSrc;
        modalTitle.innerHTML = `<i class="bi bi-image me-2"></i>产品预览图 - ${productName || '未知产品'}`;
        
        // 显示模态框
        modal.show();
        
        // 图片加载错误处理
        previewImg.onerror = function() {
            this.src = '';
            modalTitle.innerHTML = `<i class="bi bi-exclamation-triangle me-2"></i>图片加载失败 - ${productName || '未知产品'}`;
        };
    }
    
    // 全选/取消全选功能
    document.getElementById('selectAll').addEventListener('change', function() {
        const checkboxes = document.querySelectorAll('.product-checkbox');
        checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
        updateBatchDownloadButton();
    });
    
    // 监听单个复选框变化
    document.querySelectorAll('.product-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', updateBatchDownloadButton);
    });
    
    // 更新批量下载按钮状态
    function updateBatchDownloadButton() {
        const checkedBoxes = document.querySelectorAll('.product-checkbox:checked');
        const batchDownloadBtn = document.getElementById('batchDownloadBtn');
        
        if (checkedBoxes.length > 0) {
            batchDownloadBtn.disabled = false;
            batchDownloadBtn.innerHTML = `<i class="bi bi-download me-2"></i>批量下载选中项 (${checkedBoxes.length})`;
        } else {
            batchDownloadBtn.disabled = true;
            batchDownloadBtn.innerHTML = '<i class="bi bi-download me-2"></i>批量下载选中项';
        }
    }
    
    // 文件类型按钮切换
    document.querySelectorAll('.file-type-buttons .btn').forEach(btn => {
        btn.addEventListener('click', function() {
            // 移除所有按钮的active类
            document.querySelectorAll('.file-type-buttons .btn').forEach(b => b.classList.remove('active'));
            // 为当前按钮添加active类
            this.classList.add('active');
        });
    });
    
    // 批量下载功能 - 修复为使用POST请求
    document.getElementById('batchDownloadBtn').addEventListener('click', function() {
        const checkedBoxes = document.querySelectorAll('.product-checkbox:checked');
        if (checkedBoxes.length === 0) {
            showToast('请先选择要下载的产品', 'warning');
            return;
        }
        
        const productIds = Array.from(checkedBoxes).map(cb => cb.value);
        const activeFileType = document.querySelector('.file-type-buttons .btn.active').dataset.fileType;
        
        // 先检查文件大小
        checkBatchFileSize(productIds, activeFileType, () => {
            // 检查通过，显示下载提示
            showDownloadWarning(() => {
                // 3秒后开始下载 - 使用POST请求
                setTimeout(() => {
                    // 创建表单并提交
                    const form = document.createElement('form');
                    form.method = 'POST';
                    form.action = `{% url 'clamps:batch_download' 'FILETYPE' %}`.replace('FILETYPE', activeFileType);
                    
                    // 添加CSRF token
                    const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]');
                    if (csrfToken) {
                        const csrfInput = document.createElement('input');
                        csrfInput.type = 'hidden';
                        csrfInput.name = 'csrfmiddlewaretoken';
                        csrfInput.value = csrfToken.value;
                        form.appendChild(csrfInput);
                    }
                    
                    // 添加产品ID参数
                    const productIdsInput = document.createElement('input');
                    productIdsInput.type = 'hidden';
                    productIdsInput.name = 'product_ids';
                    productIdsInput.value = productIds.join(',');
                    form.appendChild(productIdsInput);
                    
                    // 提交表单
                    document.body.appendChild(form);
                    form.submit();
                    document.body.removeChild(form);
                }, 3000);
            });
        });
    });
    
    // 为PDF和STEP下载按钮添加延迟下载功能 - 增加文件大小检查
    document.querySelectorAll('.delayed-download').forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const downloadUrl = this.href;
            const productId = this.dataset.productId;
            const fileType = this.dataset.fileType;
            
            // 先检查文件大小
            checkFileSize(productId, fileType, () => {
                // 检查通过，显示下载提示
                showDownloadWarning(() => {
                    // 3秒后开始下载
                    setTimeout(() => {
                        // 检查下载是否成功，如果失败则返回当前页面
                        const iframe = document.createElement('iframe');
                        iframe.style.display = 'none';
                        iframe.src = downloadUrl;
                        document.body.appendChild(iframe);
                        
                        // 监听iframe加载完成
                        iframe.onload = function() {
                            // 检查是否跳转到了错误页面或详情页面
                            try {
                                const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                                if (iframeDoc.title.includes('产品详情') || iframeDoc.body.innerHTML.includes('下载失败')) {
                                    // 下载失败，保持在当前页面
                                    console.log('下载失败，保持在当前页面');
                                }
                            } catch (e) {
                                // 跨域或其他错误，假设下载成功
                                console.log('下载请求已发送');
                            }
                            
                            // 清理iframe
                            setTimeout(() => {
                                document.body.removeChild(iframe);
                            }, 1000);
                        };
                    }, 3000);
                });
            });
        });
    });
    
    // 检查单个文件大小
    function checkFileSize(productId, fileType, callback) {
        fetch(`{% url 'clamps:check_file_size' 0 'TYPE' %}`.replace('0', productId).replace('TYPE', fileType))
            .then(response => response.json())
            .then(data => {
                if (data.can_download) {
                    callback();
                } else {
                    showToast(`文件大小超过单次下载限制（${data.total_size}）`, 'danger');
                }
            })
            .catch(error => {
                console.error('检查文件大小时出错:', error);
                showToast('检查文件大小时出错，请稍后重试', 'danger');
            });
    }
    
    // 检查批量下载文件大小 - 修复为使用POST请求
    function checkBatchFileSize(productIds, fileType, callback) {
        const formData = new FormData();
        formData.append('product_ids', productIds.join(','));
        formData.append('file_type', fileType);
        
        // 添加CSRF token
        const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]');
        if (csrfToken) {
            formData.append('csrfmiddlewaretoken', csrfToken.value);
        }
        
        fetch('{% url "clamps:check_batch_file_size" %}', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                if (data.can_download) {
                    callback();
                } else {
                    showToast(`文件大小超过单次下载限制（${data.total_size}）`, 'danger');
                }
            })
            .catch(error => {
                console.error('检查批量文件大小时出错:', error);
                showToast('检查文件大小时出错，请稍后重试', 'danger');
            });
    }
    
    function showDownloadWarning(callback) {
        const warningHtml = `
            <div class="modal fade" id="downloadWarningModal" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">
                                <i class="bi bi-download me-2"></i>
                                下载提示
                            </h5>
                        </div>
                        <div class="modal-body">
                            <div class="alert" style="background-color: #e0f7fa; border: 1px solid #b2ebf2; border-radius: 8px; color: #2c3e50; padding: 12px 16px;">
                                <i class="bi bi-info-circle me-2" style="color: #2c3e50;"></i>
                                图纸模型数据由于各种原因发生变更后不另行通知，选型数据库无法保证图纸模型数据完全正确，该数据不作为任何参考依据。
                            </div>
                            <div class="text-center">
                                <div class="spinner-border text-primary me-2" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <span id="countdown">3</span> 秒后自动开始下载...<br>数据较多时服务器压缩需要时间，请耐心等待
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-primary" id="directDownloadBtn">
                                <i class="bi bi-download me-1"></i>
                                如窗口没有自动跳转点此直接下载
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // 移除已存在的模态框
        const existingModal = document.getElementById('downloadWarningModal');
        if (existingModal) {
            existingModal.remove();
        }
        
        document.body.insertAdjacentHTML('beforeend', warningHtml);
        const modal = new bootstrap.Modal(document.getElementById('downloadWarningModal'));
        
        let countdown = 3;
        const countdownElement = document.getElementById('countdown');
        const directDownloadBtn = document.getElementById('directDownloadBtn');
        
        const timer = setInterval(() => {
            countdown--;
            countdownElement.textContent = countdown;
            if (countdown <= 0) {
                clearInterval(timer);
                modal.hide();
                callback();
            }
        }, 1000);
        
        directDownloadBtn.addEventListener('click', () => {
            clearInterval(timer);
            modal.hide();
            callback();
        });
        
        modal.show();
        
        // 模态框关闭时清理定时器
        document.getElementById('downloadWarningModal').addEventListener('hidden.bs.modal', () => {
            clearInterval(timer);
            document.getElementById('downloadWarningModal').remove();
        });
    }
    
    function showToast(message, type = 'info') {
        const toastHtml = `
            <div class="alert alert-${type} alert-dismissible fade show fade-in-up position-fixed top-0 start-50 translate-middle-x mt-3" role="alert" style="z-index: 9999;">
                <i class="bi bi-${type === 'danger' ? 'exclamation-triangle' : type === 'warning' ? 'exclamation-circle' : 'info-circle'} me-2"></i>
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        
        document.body.insertAdjacentHTML('beforeend', toastHtml);
        
        // 自动清理alert元素
        setTimeout(() => {
            const alertElement = document.querySelector('.alert.fade-in-up');
            if (alertElement) {
                alertElement.remove();
            }
        }, 5000);
    }
</script>

<!-- 添加CSRF token到页面中供JavaScript使用 -->
{% csrf_token %}
{% endblock %}

